<template>
  <el-card class="form-container" shadow="never">
    <el-tree
      :data="menuTreeList"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      :props="defaultProps"
      v-loading="loading"
    ></el-tree>
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave()">保存</el-button>
      <el-button @click="handleClear()">清空</el-button>
    </div>
  </el-card>
</template>

<script>
import { axios } from "../../utils";

export default {
  name: "allocMenu",
  title: "角色菜单管理",
  data() {
    return {
      menuTreeList: [], //菜单数据
      checkedMenuId: [], //被选中的菜单
      loading: false, // 加载刷新组件
      //树形结构子节点设置
      defaultProps: {
        children: "subMenuList",
        label: "name",
      },
      roleId: null,
    };
  },
  //钩子函数
  created() {
    //获取路由携带的id
    this.roleId = this.$route.query.roleId;

    //获取菜单列表
    this.treeList();

    //获取角色所拥有的菜单信息
    this.getRoleMenu(this.roleId);
  },
  methods: {
    //方法1: 获取菜单列表,使用树形控件展示
    treeList() {
      this.loading = true;
      // 后端给前端返回树形结构，也就是递归出来的树形的结构 然后前端使用树型控件
      axios
        .get("role/findAllMenu")
        .then((resp) => {
          console.log(resp);
          this.menuTreeList = resp.data.content.parentMenuList;
          this.loading = false;
        })
        .catch((error) => {
          this.$message.error("获取菜单数据失败");
        });
    },

    //方法2: 获取当前角色所拥有菜单列表id
    //实质上将获取的角色对应的菜单列表进行回显
    getRoleMenu(roleId) {
      axios
        .get("menu/findMenuByRoleId/" + roleId)
        .then(() => {
          this.checkedMenuId = resp.data.content;
        })
        .catch(() => {
          this.$message.error("获取菜单列表的id失败")
        });
    },

    //方法3: 修改角色所拥有的菜单列表
    handleSave() {},

    //清空选择
    handleClear() {
      this.$refs.tree.setCheckedKeys([]);
    },
  },
};
</script>

<style scoped>
</style>
